﻿using BridgeWeChat.Constant;
using BridgeWeChat.Model;
using BridgeWebSystemLib.Core.Net;
using BridgeWebSystemLib.Core.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BridgeWeChatApiService.Controllers
{
    /// <summary>
    /// 个推消息
    /// </summary>
    [ApiController]
    public class GeTuiController : ControllerBase
    {
        private readonly IMemoryCache _cache;
        public GeTuiController(IMemoryCache cache)
        {
            _cache = cache;
        }

        /// <summary>
        /// 获取鉴权token
        /// </summary>
        [AllowAnonymous]
        [HttpPost("GetToken")]
        public string GetToken()
        {
            return _cache.GetOrCreate(CacheKeys.GeTuiToken, entry =>
            {
                string appId = HPDHttpContext.AppSettings.Value.GeTui.appId;
                string appKey = HPDHttpContext.AppSettings.Value.GeTui.appKey;
                string masterSecret = HPDHttpContext.AppSettings.Value.GeTui.masterSecret;
                string strUrl = string.Format("https://restapi.getui.com/v2/{0}/auth", appId);

                string timestamp = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds().ToString();
                GeTuiToken geTuiToken = new GeTuiToken();
                geTuiToken.sign = CryptoUtil.SHA256Hash(appKey + timestamp + masterSecret);
                geTuiToken.timestamp = timestamp;
                geTuiToken.appkey = appKey;

                var token = RestSharpAccess.Post(strUrl, geTuiToken);
                var response = JsonUtil.JsonDeserialize<TokenResponse>(token);
                if (response.code == "0")
                {
                    //比官方过期时间提前1小时就结束
                    DateTime startTime = new DateTime(1970, 1, 1, 8, 0, 0).AddHours(-1);
                    DateTime dt = startTime.AddMilliseconds(long.Parse(response.data.expire_time));
                    entry.AbsoluteExpirationRelativeToNow = dt - DateTime.Now;
                }
                else
                {
                    entry.Dispose();
                    return response.msg;
                }
                return response.data.token;
            });
        }

        /// <summary>
        /// 执行cid单推
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("SinglePush")]
        public string SinglePush(string cid,string title,string body)
        {
            SinglePushRequest request = new SinglePushRequest();
            request.request_id = "100000000021";
            request.audience.cid = new List<string> { cid };
            request.push_message.notification = new Notification() { title = title, body = body, click_type = "none" };
            var jsonRequest =  JsonUtil.JsonSerializeObject(request);
            
            string appId = HPDHttpContext.AppSettings.Value.GeTui.appId;
            string strUrl = string.Format("https://restapi.getui.com/v2/{0}/push/single/cid", appId);

            var tokenValue = GetToken();
            var dict = new Dictionary<string, string>();
            dict.Add("token", tokenValue);

            var responseString = RestSharpAccess.Post(strUrl, jsonRequest, dict);
            var response = JsonUtil.JsonDeserialize<SinglePushResponse>(responseString);
            if (response.code == "0")
            {
                JObject o = JObject.Parse(responseString);
                var jdata = o["data"] as JObject;
                response.data.taskid = jdata.Properties().First().Name;
                response.data.state = jdata.Properties().First().Value.ToString();
                return response.data.taskid;
            }
            else
            {
                return response.msg;
            }
        }

        /// <summary>
        /// 创建模板消息，为批量推的前置步骤
        /// </summary>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("CreateGeTuiTemplateMessage")]
        public GeTuiTemplateMessageResponse CreateGeTuiTemplateMessage(string title, string body)
        {
            string appId = HPDHttpContext.AppSettings.Value.GeTui.appId;
            string strUrl = string.Format("https://restapi.getui.com/v2/{0}/push/list/message", appId);
            GeTuiTemplateMessageRequest request = new GeTuiTemplateMessageRequest();
            request.request_id = "100000000023";
            request.push_message.notification = new Notification() { title = title, body = body, click_type = "none" };
            var jsonRequest = JsonUtil.JsonSerializeObject(request);

            var tokenValue = GetToken();
            var dict = new Dictionary<string, string>();
            dict.Add("token", tokenValue);

            var responseString = RestSharpAccess.Post(strUrl, jsonRequest, dict);
            return JsonUtil.JsonDeserialize<GeTuiTemplateMessageResponse>(responseString);
        }
        /// <summary>
        /// 执行cid批量推
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("ListPush")]
        public string ListPush(string[] cids, string title, string body)
        {
            var tmResponse = CreateGeTuiTemplateMessage(title, body);
            if (tmResponse.code == "0")
            {
                ListPushRequest request = new ListPushRequest();
                request.audience.cid = cids.ToList();
                request.taskid = tmResponse.data.taskid;
                request.is_async = true;
                var jsonRequest = JsonUtil.JsonSerializeObject(request);

                string appId = HPDHttpContext.AppSettings.Value.GeTui.appId;
                string strUrl = string.Format("https://restapi.getui.com/v2/{0}/push/list/cid", appId);

                var tokenValue = GetToken();
                var dict = new Dictionary<string, string>();
                dict.Add("token", tokenValue);

                var responseString = RestSharpAccess.Post(strUrl, jsonRequest, dict);
                return responseString;
            }
            else
            {
                return "创建模板消息失败！";
            }
        }

        /// <summary>
        /// 执行群推
        /// </summary>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("AllPush")]
        public string AllPush(string title, string body)
        {
            AllPushRequest request = new AllPushRequest();
            request.request_id = "100000000024";
            request.push_message.notification = new Notification() { title = title, body = body, click_type = "none" };

            var jsonRequest = JsonUtil.JsonSerializeObject(request);

            string appId = HPDHttpContext.AppSettings.Value.GeTui.appId;
            string strUrl = string.Format("https://restapi.getui.com/v2/{0}/push/all", appId);

            var tokenValue = GetToken();
            var dict = new Dictionary<string, string>();
            dict.Add("token", tokenValue);

            var responseString = RestSharpAccess.Post(strUrl, jsonRequest, dict);
            return responseString;
        }
    }
}
